package learn.design.patterns.B_Prototype;

import lombok.Getter;
import lombok.Setter;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

@Setter
@Getter
public class Prototype implements Cloneable, Serializable {
    private String data;
    private List<String> list; // 引用对象

    public Prototype(String data) {
        this.data = data;
        this.list = new ArrayList<>();
        list.add("Initial Item");
    }

    // 浅复制
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    // 深复制 - 使用序列化和反序列化
    public Prototype deepClone() throws IOException, ClassNotFoundException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(this);

        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
        return (Prototype) objectInputStream.readObject();
    }
}
